package com.robotserver.orders.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jd.open.api.sdk.JdClient;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.entity.JdTokens;
import com.robotserver.orders.entity.VipOrders;
import com.robotserver.orders.entity.VipTokens;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.mapper.VipOrdersMapper;
import com.robotserver.orders.mapper.VipTokensMapper;
import com.robotserver.orders.service.VipOrderSyncService;
import com.robotserver.orders.vo.VipOrderTimeVO;
import com.vip.adp.api.open.service.*;
import com.vip.osp.sdk.context.InvocationContext;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2020/12/2 14:05
 * @Description:
 */
@Service
public class VipOrderSyncServiceImpl implements VipOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(VipOrderSyncServiceImpl.class);

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private VipTokensMapper vipTokensMapper;
    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private VipOrdersMapper vipOrdersMapper;

    @Value("${vip.service.url}")
    private String vipServiceUrl;

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder(List<VipOrderTimeVO> vipOrderTimeVOS, List<VipTokens> vipTokens, String lockName,Integer downType) {
        threadLockSyncOrder(vipOrderTimeVOS,vipTokens,lockName,downType);
    }

    @Override
    public void threadLockSyncOrder(List<VipOrderTimeVO> vipOrderTimeVOS, List<VipTokens> vipTokens, String lockName,Integer downType) {
        if (vipTokens.size()>0){
            VipTokens token = null;
            RLock lock = null;
            try {
                lock = redissonClient.getLock(lockName);
                lock.lock();
                token = vipTokens.get(0);
                // 删除对象
                vipTokens.remove(token);
            } catch (Exception e) {
                logger.error("err:{}",e);
            } finally {
                if (lock!=null){
                    lock.unlock();
                }
            }

            if (token!=null){
                logger.info(lockName+"::viptoken>"+token.getOpenId()+"::size:"+vipTokens.size());
                syncOpenUnitOrder(vipOrderTimeVOS,token,downType);
                threadLockSyncOrder(vipOrderTimeVOS,vipTokens,lockName,downType);
            }
        }
    }

    @Override
    public void syncOpenUnitOrder(List<VipOrderTimeVO> vipOrderTimeVOS, VipTokens token,Integer downType) {
        for (VipOrderTimeVO time:vipOrderTimeVOS){
            syncTimeUnitOrder(time,token,1, downType);
        }
    }

    private void syncTimeUnitOrder(VipOrderTimeVO time, VipTokens token, int page,Integer downType) {
        try {
            String vip_app_key = sysSettingMapper.getByKey("vip_app_key");
            String vip_app_secret = sysSettingMapper.getByKey("vip_app_secret");

            UnionOrderServiceHelper.UnionOrderServiceClient client = new UnionOrderServiceHelper.UnionOrderServiceClient();
            InvocationContext invocationContext = InvocationContext.Factory.getInstance();
            invocationContext.setAppKey(vip_app_key);
            invocationContext.setAppSecret(vip_app_secret);
            invocationContext.setAppURL(vipServiceUrl);
            invocationContext.setAccessToken(token.getAccessToken());
            invocationContext.setLanguage("zh");
            OrderQueryModel queryModel = new OrderQueryModel();
            queryModel.setPage(page);
            queryModel.setRequestId(IdWorker.getIdStr());
            if (downType!=null && downType==1){
                queryModel.setOrderTimeStart(time.getBeginTime());
                queryModel.setOrderTimeEnd(time.getEndTime());
            }else{
                queryModel.setUpdateTimeStart(time.getBeginTime());
                queryModel.setUpdateTimeEnd(time.getEndTime());
            }
            OrderResponse response = client.orderListWithOauth(queryModel);

            if (response!=null && response.getOrderInfoList()!=null && response.getOrderInfoList().size()>0){
                // 处理订单入库
                ordersAdd(response.getOrderInfoList(),token);
                page = page+1;
                syncTimeUnitOrder(time, token, page, downType);
            }
        } catch (Exception e) {
            logger.error("vip sync order, token={} , err:{}", token.getAccessToken(), e.getMessage());
        }
    }

    @Override
    public void ordersAdd(List<OrderInfo> orderInfoList,VipTokens vipTokens) {
        for (OrderInfo orderInfo:orderInfoList){

            //自定义参数不为空，且以cps_开头，这种订单为推老板订单，不入库
            String statParam = orderInfo.getStatParam();
            if(StringUtils.isNotBlank(statParam) && statParam.startsWith("cps_")) {
                logger.info("---VIP cps orders orderSn:{}, OrderSubStatusName:{}, statParam={},",new Object[]{orderInfo.getOrderSn(),orderInfo.getOrderSubStatusName(), statParam});
                continue;
            }

            List<OrderDetailInfo> orderDetailInfos = orderInfo.getDetailList();
            if(orderDetailInfos == null || orderDetailInfos.size() == 0){
                logger.info("---VIP orders orderSn:{}, OrderSubStatusName:{}, getDetailListSize={},",new Object[]{orderInfo.getOrderSn(),orderInfo.getOrderSubStatusName(), orderInfo.getDetailList()==null?0:orderInfo.getDetailList().size()});
                continue;
            }

            if(orderDetailInfos != null){
                for (OrderDetailInfo orderDetailInfo:orderDetailInfos){
                    try {
                        logger.info("---VIP orders orderSn:{},goodsId:{},status:{},OrderSubStatusName:{}",new Object[]{orderInfo.getOrderSn(),orderDetailInfo.getGoodsId(),orderDetailInfo.getStatus(),orderInfo.getOrderSubStatusName()});

                        // 根据订单号查询商品是否存在
                        VipOrders vipOrders = vipOrdersMapper.getByOrderSn(orderInfo.getOrderSn(),orderDetailInfo.getGoodsId(),orderDetailInfo.getSizeId());
                        if (vipOrders==null && orderDetailInfo.getStatus()==0){
                            // 不合格
                            // continue;
                        }
                        int bizstatus = bizStatus(orderInfo.getOrderSubStatusName());
                        if (bizstatus==-1){
                            //continue;
                        }
                        int now = DateUtil.getNowTime();

                        List<AfterSaleDetailInfo> afterSaleDetailInfos = orderDetailInfo.getAfterSaleInfo();
                        AfterSaleDetailInfo afterSaleDetailInfo = null;
                        if (afterSaleDetailInfos!=null && afterSaleDetailInfos.size()>0){
                            afterSaleDetailInfo = afterSaleDetailInfos.get(0);
                        }

                        if (vipOrders==null){
//                        if ((bizstatus==0 || bizstatus==1)
//                                && (afterSaleDetailInfo==null ||
//                                afterSaleDetailInfo.getAfterSaleType().intValue()!=1)){
                            // 订单为付款或者结算 && 没有售后信息或者不是退货
                            vipOrders = new VipOrders();
                            vipOrders.setId(IdWorker.getId());
                            vipOrders.setOrderSn(orderInfo.getOrderSn());
                            vipOrders.setStatus(orderInfo.getStatus().intValue());
                            vipOrders.setNewCustomer(orderInfo.getNewCustomer()!=null?orderInfo.getNewCustomer().intValue():null);
                            vipOrders.setChannelTag(orderInfo.getChannelTag());
                            vipOrders.setOrderTime(orderInfo.getOrderTime()!=null?(int)(orderInfo.getOrderTime()/1000):null);
                            vipOrders.setSignTime(orderInfo.getSignTime()!=null?(int)(orderInfo.getSignTime()/1000):null);
                            vipOrders.setSettledTime(orderInfo.getSettledTime()!=null?(int)(orderInfo.getSettledTime()/1000):null);
                            vipOrders.setGoodsId(orderDetailInfo.getGoodsId());
                            vipOrders.setGoodsName(orderDetailInfo.getGoodsName());
                            vipOrders.setGoodsThumb(orderDetailInfo.getGoodsThumb());
                            vipOrders.setGoodsCount(orderDetailInfo.getGoodsCount());
                            vipOrders.setCommissionTotalCost(orderDetailInfo.getCommissionTotalCost()!=null?Double.parseDouble(orderDetailInfo.getCommissionTotalCost()):null);
                            vipOrders.setCommissionRate(orderDetailInfo.getCommissionRate()!=null?Double.parseDouble(orderDetailInfo.getCommissionRate()):null);
                            vipOrders.setGoodsCommission(orderDetailInfo.getCommission()!=null?Double.parseDouble(orderDetailInfo.getCommission()):null);
                            vipOrders.setCommCode(orderDetailInfo.getCommCode());
                            vipOrders.setCommName(orderDetailInfo.getCommName());
                            vipOrders.setGoodsOrderSource(orderDetailInfo.getOrderSource());
                            vipOrders.setSizeId(orderDetailInfo.getSizeId());
                            vipOrders.setGoodsStatus(orderDetailInfo.getStatus().intValue());
                            vipOrders.setBrandStoreSn(orderDetailInfo.getBrandStoreSn());
                            vipOrders.setBrandStoreName(orderDetailInfo.getBrandStoreName());
                            vipOrders.setSpuId(orderDetailInfo.getSpuId());
                            vipOrders.setLastUpdateTime(orderInfo.getLastUpdateTime()!=null?(int)(orderInfo.getLastUpdateTime()/1000):null);
                            vipOrders.setSettled(orderInfo.getSettled()!=null?orderInfo.getSettled().intValue():null);
                            vipOrders.setSelfBuy(orderInfo.getSelfBuy());
                            vipOrders.setOrderSubStatusName(orderInfo.getOrderSubStatusName());
                            vipOrders.setCommission(orderInfo.getCommission()!=null?Double.parseDouble(orderInfo.getCommission()):null);
                            vipOrders.setAfterSaleChangeCommission(orderInfo.getAfterSaleChangeCommission()!=null?Double.parseDouble(orderInfo.getAfterSaleChangeCommission()):null);
                            vipOrders.setAfterSaleChangeGoodsCount(orderInfo.getAfterSaleChangeGoodsCount());
                            vipOrders.setCommissionEnterTime(orderInfo.getCommissionEnterTime()!=null?(int)(orderInfo.getCommissionEnterTime()/1000):null);
                            vipOrders.setOrderSource(orderInfo.getOrderSource());
                            vipOrders.setPid(orderInfo.getPid());
                            vipOrders.setIsPrepay(orderInfo.getIsPrepay());
                            vipOrders.setStatParam(orderInfo.getStatParam());
                            vipOrders.setIsSplit(orderInfo.getIsSplit());
                            vipOrders.setParentSn(orderInfo.getParentSn());
                            vipOrders.setOrderTrackReason(orderInfo.getOrderTrackReason());
                            vipOrders.setAppKey(orderInfo.getAppKey());
                            vipOrders.setCreateTime(now);
                            vipOrders.setUpdateTime(now);
                            vipOrders.setBizStatus(bizstatus);
                            vipOrders.setOpenid(vipTokens.getOpenId());

                            vipOrdersMapper.add(vipOrders);

                            logger.info("---VIP orders add orderSn:{},goodsId:{},status:{},OrderSubStatusName:{}",new Object[]{orderInfo.getOrderSn(),orderDetailInfo.getGoodsId(),orderDetailInfo.getStatus(),orderInfo.getOrderSubStatusName()});

//                        }
                        }else {

                            //订单失效或者订单已维权，则不修改
                            if(vipOrders.getBizStatus().intValue() == 2 || vipOrders.getBizStatus().intValue() == 3){
                                continue;
                            }

                            if (afterSaleDetailInfo!=null &&
                                    afterSaleDetailInfo.getAfterSaleType().intValue()==1 &&
                                    afterSaleDetailInfo.getAfterSaleStatus().intValue()==2){
                                // 订单维权退款改成失效订单
                                bizstatus=2;
                            }


                            if (bizstatus==vipOrders.getBizStatus().intValue()){
                                // 状态相同不处理
                                // continue;
                            }

                            //失效订单且已结算则改成维权
                            if (bizstatus==2 && vipOrders.getBizStatus().intValue()==1){
                                // 订单维权退款
                                vipOrders.setStatus(orderInfo.getStatus().intValue());
                                vipOrders.setNewCustomer(orderInfo.getNewCustomer()!=null?orderInfo.getNewCustomer().intValue():null);
                                vipOrders.setChannelTag(orderInfo.getChannelTag());
                                vipOrders.setOrderTime(orderInfo.getOrderTime()!=null?(int)(orderInfo.getOrderTime()/1000):null);
                                vipOrders.setSignTime(orderInfo.getSignTime()!=null?(int)(orderInfo.getSignTime()/1000):null);
                                vipOrders.setSettledTime(orderInfo.getSettledTime()!=null?(int)(orderInfo.getSettledTime()/1000):null);
                                vipOrders.setGoodsId(orderDetailInfo.getGoodsId());
                                vipOrders.setGoodsName(orderDetailInfo.getGoodsName());
                                vipOrders.setGoodsThumb(orderDetailInfo.getGoodsThumb());
                                vipOrders.setGoodsCount(orderDetailInfo.getGoodsCount());
                                vipOrders.setCommissionTotalCost(orderDetailInfo.getCommissionTotalCost()!=null?Double.parseDouble(orderDetailInfo.getCommissionTotalCost()):null);
                                vipOrders.setCommissionRate(orderDetailInfo.getCommissionRate()!=null?Double.parseDouble(orderDetailInfo.getCommissionRate()):null);
                                vipOrders.setGoodsCommission(orderDetailInfo.getCommission()!=null?Double.parseDouble(orderDetailInfo.getCommission()):null);
                                vipOrders.setCommCode(orderDetailInfo.getCommCode());
                                vipOrders.setCommName(orderDetailInfo.getCommName());
                                vipOrders.setGoodsOrderSource(orderDetailInfo.getOrderSource());
                                vipOrders.setSizeId(orderDetailInfo.getSizeId());
                                vipOrders.setGoodsStatus(orderDetailInfo.getStatus().intValue());
                                vipOrders.setBrandStoreSn(orderDetailInfo.getBrandStoreSn());
                                vipOrders.setBrandStoreName(orderDetailInfo.getBrandStoreName());
                                vipOrders.setSpuId(orderDetailInfo.getSpuId());
                                vipOrders.setLastUpdateTime(orderInfo.getLastUpdateTime()!=null?(int)(orderInfo.getLastUpdateTime()/1000):null);
                                vipOrders.setSettled(orderInfo.getSettled()!=null?orderInfo.getSettled().intValue():null);
                                vipOrders.setSelfBuy(orderInfo.getSelfBuy());
                                vipOrders.setOrderSubStatusName(orderInfo.getOrderSubStatusName());
                                vipOrders.setCommission(orderInfo.getCommission()!=null?Double.parseDouble(orderInfo.getCommission()):null);
                                vipOrders.setAfterSaleChangeCommission(orderInfo.getAfterSaleChangeCommission()!=null?Double.parseDouble(orderInfo.getAfterSaleChangeCommission()):null);
                                vipOrders.setAfterSaleChangeGoodsCount(orderInfo.getAfterSaleChangeGoodsCount());

                                vipOrders.setCommissionEnterTime(orderInfo.getCommissionEnterTime()!=null?(int)(orderInfo.getCommissionEnterTime()/1000):null);
                                vipOrders.setOrderSource(orderInfo.getOrderSource());
                                vipOrders.setPid(orderInfo.getPid());
                                vipOrders.setIsPrepay(orderInfo.getIsPrepay());
                                vipOrders.setStatParam(orderInfo.getStatParam());
                                vipOrders.setIsSplit(orderInfo.getIsSplit());
                                vipOrders.setParentSn(orderInfo.getParentSn());
                                vipOrders.setOrderTrackReason(orderInfo.getOrderTrackReason());
                                vipOrders.setAppKey(orderInfo.getAppKey());
                                vipOrders.setUpdateTime(now);
                                vipOrders.setBizStatus(3); //改成维权
                                vipOrdersMapper.update(vipOrders);

                                logger.info("---VIP orders refound update orderSn:{},goodsId:{},status:{},OrderSubStatusName:{}",new Object[]{orderInfo.getOrderSn(),orderDetailInfo.getGoodsId(),orderDetailInfo.getStatus(),orderInfo.getOrderSubStatusName()});

                            }else{ //失效订单且不结算则改成失效订单
                                vipOrders.setStatus(orderInfo.getStatus().intValue());
                                vipOrders.setNewCustomer(orderInfo.getNewCustomer()!=null?orderInfo.getNewCustomer().intValue():null);
                                vipOrders.setChannelTag(orderInfo.getChannelTag());
                                vipOrders.setOrderTime(orderInfo.getOrderTime()!=null?(int)(orderInfo.getOrderTime()/1000):null);
                                vipOrders.setSignTime(orderInfo.getSignTime()!=null?(int)(orderInfo.getSignTime()/1000):null);
                                vipOrders.setSettledTime(orderInfo.getSettledTime()!=null?(int)(orderInfo.getSettledTime()/1000):null);
                                vipOrders.setGoodsId(orderDetailInfo.getGoodsId());
                                vipOrders.setGoodsName(orderDetailInfo.getGoodsName());
                                vipOrders.setGoodsThumb(orderDetailInfo.getGoodsThumb());
                                vipOrders.setGoodsCount(orderDetailInfo.getGoodsCount());
                                vipOrders.setCommissionTotalCost(orderDetailInfo.getCommissionTotalCost()!=null?Double.parseDouble(orderDetailInfo.getCommissionTotalCost()):null);
                                vipOrders.setCommissionRate(orderDetailInfo.getCommissionRate()!=null?Double.parseDouble(orderDetailInfo.getCommissionRate()):null);
                                vipOrders.setGoodsCommission(orderDetailInfo.getCommission()!=null?Double.parseDouble(orderDetailInfo.getCommission()):null);
                                vipOrders.setCommCode(orderDetailInfo.getCommCode());
                                vipOrders.setCommName(orderDetailInfo.getCommName());
                                vipOrders.setGoodsOrderSource(orderDetailInfo.getOrderSource());
                                vipOrders.setSizeId(orderDetailInfo.getSizeId());
                                vipOrders.setGoodsStatus(orderDetailInfo.getStatus().intValue());
                                vipOrders.setBrandStoreSn(orderDetailInfo.getBrandStoreSn());
                                vipOrders.setBrandStoreName(orderDetailInfo.getBrandStoreName());
                                vipOrders.setSpuId(orderDetailInfo.getSpuId());
                                vipOrders.setLastUpdateTime(orderInfo.getLastUpdateTime()!=null?(int)(orderInfo.getLastUpdateTime()/1000):null);
                                vipOrders.setSettled(orderInfo.getSettled()!=null?orderInfo.getSettled().intValue():null);
                                vipOrders.setSelfBuy(orderInfo.getSelfBuy());
                                vipOrders.setOrderSubStatusName(orderInfo.getOrderSubStatusName());
                                vipOrders.setCommission(orderInfo.getCommission()!=null?Double.parseDouble(orderInfo.getCommission()):null);
                                vipOrders.setAfterSaleChangeCommission(orderInfo.getAfterSaleChangeCommission()!=null?Double.parseDouble(orderInfo.getAfterSaleChangeCommission()):null);
                                vipOrders.setAfterSaleChangeGoodsCount(orderInfo.getAfterSaleChangeGoodsCount());
                                vipOrders.setCommissionEnterTime(orderInfo.getCommissionEnterTime()!=null?(int)(orderInfo.getCommissionEnterTime()/1000):null);
                                vipOrders.setOrderSource(orderInfo.getOrderSource());
                                vipOrders.setPid(orderInfo.getPid());
                                vipOrders.setIsPrepay(orderInfo.getIsPrepay());
                                vipOrders.setStatParam(orderInfo.getStatParam());
                                vipOrders.setIsSplit(orderInfo.getIsSplit());
                                vipOrders.setParentSn(orderInfo.getParentSn());
                                vipOrders.setOrderTrackReason(orderInfo.getOrderTrackReason());
                                vipOrders.setAppKey(orderInfo.getAppKey());
                                vipOrders.setUpdateTime(now);
                                vipOrders.setBizStatus(bizstatus); //已失效
                                vipOrdersMapper.update(vipOrders);

                                logger.info("---VIP orders update orderSn:{},goodsId:{},status:{},OrderSubStatusName:{}",new Object[]{orderInfo.getOrderSn(),orderDetailInfo.getGoodsId(),orderDetailInfo.getStatus(),orderInfo.getOrderSubStatusName()});

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(" vip order download err: accessToken={}, orderSn={}, goodsId={}, status={}, statusName={}, err={}",
                                vipTokens.getAccessToken(), orderInfo.getOrderSn(), orderDetailInfo.getGoodsId(), orderDetailInfo.getStatus(), orderInfo.getOrderSubStatusName(), e.getMessage());
                    }
                }
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(List<VipOrderTimeVO> vipOrderTimeVOS, VipTokens token, Integer downType) {
        syncOpenUnitOrder(vipOrderTimeVOS,token,downType);
    }


    private int bizStatus(String orderSubStatusName) {
        switch (orderSubStatusName){
            case "已下单":
                return -1;
            case "已付款":
                return 0;
            case "已签收":
                return 1;
            case "待结算":
                return 1;
            case "已结算":
                return 1;
            case "已失效":
                return 2;
            case "已保价":
                return 3;
            case "已售后":
                return 3;
            case "换货":
                return 3;
        }
        return -1;
    }
}
